package module

import (
	"context"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	config "jkrb_v2.0/init"
	"jkrb_v2.0/mail"
	"log"
	"strconv"
	"time"
)

type UserDesc struct {
	gorm.Model
	UserName   string
	Token      string
	Gps        string
	Location   string
	Status     string
	Tmp        string
	Concact    string
	Pcc        string
	Auth       int
	Email      string
	Nearstatus int       `gorm:"column:nearstatus"`
	Tody       time.Time `gorm:"column:today"`
}

func (u UserDesc) TableName() string {
	return "user_descs"
}

type Res struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data string `json:"data"`
}

var Conn *gorm.DB

func GetConnect() {
	conn, err := gorm.Open("mysql", config.ConfigA.MysqlUser+":"+config.ConfigA.MysqlPwd+"@("+config.ConfigA.MysqlAdd+":"+strconv.Itoa(config.ConfigA.MysqlPort)+")/"+config.ConfigA.MysqlDatabase+"?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		log.Println(err)
		return
	}
	conn.DB().SetMaxIdleConns(1)
	conn.DB().SetMaxOpenConns(2)
	conn.DB().SetConnMaxLifetime(time.Hour * 7)
	conn.AutoMigrate(&UserDesc{})
	Conn = conn
}

func GetAllUser() []UserDesc {
	var users []UserDesc
	Conn.Table("user_descs").Where("auth =?", 1).Scan(&users)
	return users
}

func IsConnect() (x bool) {
	user := UserDesc{
		UserName: "相博",
		Email:    "1015286189@qq.com",
		Auth:     1,
	}
	defer func() {
		if r := recover(); r != nil {
			mail.Send(user, "数据库连接失败。")
			x = false
		}
	}()
	ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
	err := Conn.DB().PingContext(ctx)
	if err == nil {
		return true
	} else {
		mail.Send(user, "数据库连接失败 , "+err.Error())
		return false
	}
}
